<template>
  <div>
    <div class="Box">
      <div v-if="isquestionEd">
        <img class="isImg" src="../../assets/isWork.png" />
      </div>
      <div v-if="isOver">
        <img class="isOverImg" src="../../assets/isOver.png" />
      </div>
      <!-- 问卷标题 -->
      <div class="title">
        {{ questiondata.title }}
      </div>
      <img
        v-if="questiondata.images"
        class="headimg"
        :src="questiondata.images | questionImg"
      />
      <!-- 问卷描述 -->
      <div v-if="questiondata.describe" class="Votingtext">
        {{ questiondata.describe }}
      </div>
      <!-- 问卷视频链接 -->
      <div v-if="questiondata.videos" class="video">
        视频链接:
        <span @click="openVedio(questiondata.videos)">{{
          questiondata.videos
        }}</span>
      </div>
      <!-- 问题列表 -->
      <div class="questionlist">
        <div
          class="questionbox"
          v-for="(item, index) in selectdata"
          :key="index"
        >
          <!-- 问题标题 -->
          <div class="questionboxtitle">
            问题{{ index + 1 }}： {{ item.optiontitle }}
            <span class="tip" v-if="item.subopitonsitme">
              （可选{{ item.subopitonsitme }}个）</span
            >
          </div>
          <!-- 表单验证 -->
          <!-- 单选 -->
          <el-form
            :model="optiondata[index]"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item
              v-if="item.optiontype == 1"
              label-width="0px"
              prop="subopitonstitile"
            >
              <el-checkbox-group
                v-if="item.optiontype == 1"
                :disabled="isquestionEd || isOver"
                class="questionlist"
                v-model="optiondata[index].subopitonstitile"
                :min="0"
                :max="1"
                @change="seletchde($event, index)"
              >
                <div v-for="(el, index) in item.subopitons" :key="index">
                  <el-checkbox
                    name="subopitonstitile"
                    class="checkTitle"
                    :label="index"
                  >
                    {{ el.subopitonstitile }}</el-checkbox
                  >
                </div>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
          <!-- 表单验证 -->
          <!-- 多选 -->
          <el-form
            v-if="item.optiontype == 2"
            :model="optiondata[index]"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label-width="0px" prop="mulopitonstitile">
              <el-checkbox-group
                v-if="item.optiontype == 2"
                :disabled="isquestionEd || isOver"
                class="questionlist"
                v-model="optiondata[index].mulopitonstitile"
                :min="0"
                :max="item.subopitonsitme"
                @change="seletchde($event, index)"
              >
                <div v-for="(el, index) in item.mulopitons" :key="index">
                  <el-checkbox class="checkTitle" :label="index">
                    {{ el.subopitonstitile }}</el-checkbox
                  >
                </div>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
          <!-- 表单验证 -->
          <!-- 输入 -->
          <el-form
            v-if="item.optiontype == 3"
            :model="optiondata[index]"
            :rules="rules2"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label-width="0px" prop="subopitonstitile">
              <el-input
                v-if="item.optiontype == 3"
                :disabled="isquestionEd || isOver"
                @blur="rultInput(optiondata[index].subopitonstitile, index)"
                v-model="optiondata[index].subopitonstitile"
                placeholder="请输入内容"
                class="inputs"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="" />
      </el-dialog>
      <el-dialog
        width="1400px"
        class="elDog"
        title=""
        :visible.sync="dialogTableVisible"
      >
        <iframe
          v-if="dialogTableVisible"
          frameborder="0"
          width="1200"
          height="800"
          :src="VedioHtml"
          allowFullScreen="true"
        ></iframe>
      </el-dialog>

      <div class="bottom">
        <el-form
          :rules="rules2"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item>
            <el-button
              :disabled="isquestionEd || isOver"
              class="bottomButton"
              @click="submitForm()"
              type="primary"
              >提交投票</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { get_question, put_question } from "../../api/question";
import {
  get_question_reply,
  post_question_reply
} from "../../api/question_reply";

import { Question_img_prefix } from "../../utils/global";
// import { formatDateTime } from "../../common/Time";
export default {
  data() {
    return {
      select: [],
      selectdata: [],
      questiondata: [],
      dialogImageUrl: "",
      dialogVisible: false,
      isquestionEd: false, //是否已经提交过
      dialogTableVisible: false,
      isOver: false, //是否过了截止时间
      VedioHtml: "",
      input: "",
      result: [],
      optiondata: [],
      isok: [],
      rules: {
        subopitonstitile: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个",
            trigger: "change"
          }
        ],
        mulopitonstitile: [
          {
            type: "array",
            required: true,
            message: "请认真完善您的选择",
            trigger: "change"
          }
        ]
      },
      rules2: {
        subopitonstitile: [
          { required: true, message: "请认真完善问卷", trigger: "blur" }
        ]
      }
    };
  },
  filters: {
    questionImg(val) {
      return Question_img_prefix + val;
    }
  },
  created() {
    this.get_questiondata();
  },
  methods: {
    seletchde(e, index) {
      console.log(e, index);
      if (e.length == 0) {
        this.isok[index].isok = false;
      } else {
        this.isok[index].isok = true;
      }
    },
    rultInput(e, index) {
      if (e == "") {
        this.isok[index].isok = false;
      } else {
        this.isok[index].isok = true;
      }
    },
    async get_questiondata() {
      var req_question_reply = {
        query: {
          question_id: this.$route.query._id,
          user_id: this.$store.getters.userInfo._id
        }
      };
      var question_reply = await get_question_reply(req_question_reply);
      console.log("填写完成的信息", question_reply);

      console.log(this.isquestionEd);

      console.log(this.$route.query);
      var questiondata = await get_question({ query: this.$route.query });
      console.log(questiondata);
      this.questiondata = questiondata.data[0];
      this.selectdata = questiondata.data[0].option;

      //判断是否过期
      var nowtime = Date.parse(new Date());
      var endtime = Date.parse(questiondata.data[0].endtime);
      if (nowtime > endtime) {
        this.isOver = true;
      }

      if (question_reply.data.length !== 0) {
        this.isquestionEd = true;
        console.log(question_reply.data[0]);
        this.optiondata = question_reply.data[0].option;
      } else {
        //创建一个装问卷答案的json数组
        var optiondata = [];
        var isok = [];
        for (let index = 0; index < this.selectdata.length; index++) {
          const element = this.selectdata[index];
          if (element.optiontype == 3) {
            optiondata.push({
              optiontitle: element.optiontitle, //选项标题
              optiontype: element.optiontype, //选择类型 1单选 2多选 3填空
              subopitonstitile: "", //选择的子选项标题   填空选项的标题（用户填写）类型为1 3显示
              mulopitonstitile: [] //多选的子选项标题   类型2显示
            });
            isok.push({ isok: false });
          } else {
            optiondata.push({
              optiontitle: element.optiontitle, //选项标题
              optiontype: element.optiontype, //选择类型 1单选 2多选 3填空
              subopitonstitile: [], //选择的子选项标题   填空选项的标题（用户填写）类型为1 3显示
              mulopitonstitile: [] //多选的子选项标题   类型2显示
            });
            isok.push({ isok: false });
          }
        }
        this.isok = isok;
        this.optiondata = optiondata;
        console.log(this.optiondata);
      }
    },
    openVedio(vedio) {
      console.log(vedio);
      this.VedioHtml = vedio;
      this.dialogTableVisible = true;
    },
    async updateVoting() {
      console.log(this.optiondata);
      for (let index = 0; index < this.optiondata.length; index++) {
        const element = this.optiondata[index];
        if (element.optiontype == 1) {
          for (let i = 0; i < element.subopitonstitile.length; i++) {
            const el1 = element.subopitonstitile[i];
            console.log("单选index", el1);
            put_question({
              query: { _id: this.$route.query._id },
              update: {
                $inc: {
                  ["option." +
                  index +
                  ".subopitons." +
                  el1 +
                  ".subopitonsnum"]: 1
                }
              }
            });
          }
        } else if (element.optiontype == 2) {
          for (let i = 0; i < element.mulopitonstitile.length; i++) {
            const el2 = element.mulopitonstitile[i];
            console.log("多选index", el2);
            put_question({
              query: { _id: this.$route.query._id },
              update: {
                $inc: {
                  ["option." +
                  index +
                  ".mulopitons." +
                  el2 +
                  ".subopitonsnum"]: 1
                }
              }
            });
          }
        }
      }
      var select = {
        question_id: this.$route.query._id, //问卷表_id
        user_id: this.$store.getters.userInfo._id, //用户_id
        option: this.optiondata, //子选项
        option_time: new Date() //问卷时间
      };
      console.log(select);
      await post_question_reply(select);
      await put_question({
        query: { _id: this.$route.query._id },
        update: {
          $inc: { questionNum: "1" }
        }
      });
      setTimeout(this.$router.go(0), 3000);
    },
    submitForm() {
      console.log(this.isok);

      for (let index = 0; index < this.isok.length; index++) {
        const element = this.isok[index];
        if (!element.isok) {
          this.$notify({
            title: "提醒",
            message: "问卷未完善！",
            type: "warning"
          });
          return;
        }else{
        var that = this;
        this.$confirm("是否确定填写完毕? 确认后无法修改", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            that.updateVoting();
            that.$finish_taskdata(7, this.$store.getters.userInfo._id);

            this.$message({
              type: "success",
              message: "提交成功!"
            });

          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
        }
      
      }
    },
    handlePictureCardPreview(val) {
      this.dialogImageUrl = Question_img_prefix + val;
      this.dialogVisible = true;
    }
  }
};
</script>

<style lang="scss" scoped>
.Box {
  position: relative;
  width: 1000px;
  margin: 0 auto;
  background-color: #ffffff;
  height: auto;
  text-align: center;
  padding: 50px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  .title {
    width: 800px;
    margin: 0 auto;
    text-align: center;
    color: rgb(29, 47, 112);
    font-size: 30px;
    word-wrap: break-word;
  }
  .headimg {
    width: 800px;
    height: auto;
    margin: 20px auto;
    border-radius: 10px;
    border: 1px solid #b3b3b3;
  }
  .Votingtext {
    width: 800px;
    margin: 10px auto;
    word-wrap: break-word;
  }
  .video {
    width: 800px;
    margin: 10px auto;
    word-wrap: break-word;
    display: flex;
    font-weight: 550;
    font-size: 18px;
    word-wrap: break-word;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    color: rgb(29, 47, 112);
  }
  .video :hover {
    cursor: pointer;
    text-decoration: underline;
  }
  .inputs {
    margin: 30px 0;
  }
  .questionlist {
    width: 800px;
    margin: 30px auto;
    display: flex;
    flex-wrap: wrap;
    flex-direction: column;
    justify-content: center;
    .questionbox {
      position: relative;
      margin: 20px;
      padding: 10px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2), 0 0 6px rgba(0, 0, 0, 0.2);
      border-radius: 10px;
      .questionboxtitle {
        float: left;
        font-weight: 550;
        .tip {
          font-size: 12px;
        }
      }
      .votimg {
        position: absolute;
        bottom: 2px;
        right: 2px;
        z-index: 100;
        width: 53px;
        height: 44px;
      }
      .optionvideo {
        height: 40px;
        width: 134px;
        display: flex;
        font-weight: 550;
        font-size: 12px;
        word-wrap: break-word;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        color: rgb(29, 47, 112);
      }
      .optionvideo :hover {
        cursor: pointer;
        text-decoration: underline;
      }
      .openimg {
        height: 40px;
        display: flex;
        font-weight: 550;
        font-size: 15px;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        color: rgb(29, 47, 112);
      }
      .checkTitle {
        width: 700px;
        height: auto;
        margin: 10px 0;
        font-size: 19px;
        white-space: normal;
        word-break: break-all;
        display: flex;
        justify-content: flex-start;
      }
    }
  }
  .bottom {
    width: 800px;
    margin: 0 auto;
    text-align: center;
    .bottomButton {
      margin: 0 auto;
      width: 100px;
    }
  }
  .isImg {
    position: absolute;
    right: 20px;
    width: 138px;
    height: 132px;
  }
  .isOverImg {
    position: absolute;
    left: 20px;
    width: 138px;
    height: 132px;
  }
  .elDog {
  }
}
</style>
